package com.aibaixun.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aibaixun.common.constant.ApiConstants;
import com.aibaixun.common.constant.CacheConstants;
import com.aibaixun.common.core.domain.R;
import com.aibaixun.common.utils.HttpUtils;
import com.aibaixun.common.utils.redis.RedisUtils;
import com.aibaixun.system.domain.DicmAddress;
import com.aibaixun.system.domain.DicmCabinet;
import com.aibaixun.system.domain.LkMqttData;
import com.aibaixun.system.domain.PostureDevice;
import com.aibaixun.system.domain.dto.DicmAddressData;
import com.aibaixun.system.domain.dto.IndexStatisticsDto;
import com.aibaixun.system.domain.vo.CabinetUsageSituationVo;
import com.aibaixun.system.domain.vo.EnergyPueStatisticsVo;
import com.aibaixun.system.domain.vo.QueryEnergyEfficiencyVo;
import com.aibaixun.system.domain.vo.QueryLkMqttDataVo;
import com.aibaixun.system.mapper.LkMqttDataMapper;
import com.aibaixun.system.service.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hpsf.Decimal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

import java.util.stream.Collectors;

/**
 * <b>LkMqttDataServiceImpl</b>
 *
 * @description: LkMqttDataServiceImpl <br>
 * @date: 2024/5/16 17:38 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class LkMqttDataServiceImpl extends ServiceImpl<LkMqttDataMapper, LkMqttData> implements LkMqttDataService {
    private static final Logger logger = LoggerFactory.getLogger(LkMqttDataServiceImpl.class);

    @Autowired
    private DicmAddressService dicmAddressService;

    @Autowired
    private DicmCabinetService dicmCabinetService;

    @Autowired
    private PostureDeviceService postureDeviceService;

    @Autowired
    private DicmAddressDataService dicmAddressDataService;

    @Override
    public R<QueryEnergyEfficiencyVo> getEnergyPue(IndexStatisticsDto dto) {
        QueryEnergyEfficiencyVo queryEnergyEfficiencyVo = new QueryEnergyEfficiencyVo();
        Date parse = DateUtil.parse("2024-07-25 13:00:00", DatePattern.NORM_DATETIME_FORMATTER);
//        Calendar calendar1 = Calendar.getInstance();
//        calendar1.setTime(parse);
//        calendar1.add(Calendar.HOUR_OF_DAY,-1);
//        Date time1 = calendar1.getTime();
//        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH");
//        String date1 = sdf1.format(time1);
////        String nowTime = sdf1.format(new Date());
//        String nowTime = sdf1.format(new Date());
//        List<QueryLkMqttDataVo> lkMqttDataVos1 = baseMapper.queryNowMqttDateListByHour(date1);
//        if (CollectionUtil.isNotEmpty(lkMqttDataVos1)){
//            List<String> siteIdList = lkMqttDataVos1.stream().map(QueryLkMqttDataVo::getSiteId).collect(Collectors.toList());
//            Map<String, List<QueryLkMqttDataVo>> map = lkMqttDataVos1.stream().collect(Collectors.groupingBy(QueryLkMqttDataVo::getSiteId));
//            List<QueryLkMqttDataVo> lkMqttDataList = baseMapper.queryNowMqttDateListByHour(nowTime);
//            if (CollectionUtil.isNotEmpty(lkMqttDataList)){
//                Map<String, List<QueryLkMqttDataVo>> mqttDataMap = lkMqttDataList.stream().collect(Collectors.groupingBy(QueryLkMqttDataVo::getSiteId));
//                List<EnergyPueStatisticsVo> resul = getResul(map, mqttDataMap, siteIdList);
//                if (CollectionUtil.isNotEmpty(resul)){
//                    queryEnergyEfficiencyVo.setData(resul.get(0).getData());
//                }else {
//                    queryEnergyEfficiencyVo.setData("0");
//                }
//            }
//        }
        List<DicmAddress> addressList = null;
        if (StringUtils.isNotBlank(dto.getAddressId())){
            addressList = dicmAddressService.queryAddressaIdByAddressId(dto.getAddressId());
        }
        List<String> addressIdList = null;
        if (CollectionUtil.isNotEmpty(addressList)){
            addressIdList = addressList.stream().map(DicmAddress::getAddressId).collect(Collectors.toList());
        }
        List<EnergyPueStatisticsVo> resulList = new ArrayList<>();
        if (dto.getDataType() == 0){
            String date = DateUtil.format(new Date(), "yyyy-MM-dd HH");
            List<DicmAddressData> dicmAddressDataList = dicmAddressDataService.queryEnergyInfoDate(date);
            if (CollectionUtil.isEmpty(dicmAddressDataList)){
                //获取U信息
                com.alibaba.fastjson.JSONObject jsonObject = HttpUtils.sendGetRequest(ApiConstants.IP_ADDRESS
                    +ApiConstants.BLADE_ENERGY);
                if (null != jsonObject){
                    if(jsonObject.getInteger("code") == null || jsonObject.getInteger("code").intValue() != 200){
                        DicmAddressData dicmAddressData1 = new DicmAddressData();
                        DicmAddressData dicmAddressData2 = new DicmAddressData();
                        DicmAddressData dicmAddressData3 = new DicmAddressData();
                        DicmAddressData dicmAddressData4 = new DicmAddressData();
                        DicmAddressData dicmAddressData5 = new DicmAddressData();
                        DicmAddressData dicmAddressData6 = new DicmAddressData();
                        DicmAddressData dicmAddressData7 = new DicmAddressData();
                        DicmAddressData dicmAddressData8 = new DicmAddressData();
                        dicmAddressData1.setAddressName("A1");
                        dicmAddressData1.setAddressNumber("0");
                        dicmAddressData2.setAddressName("金阳");
                        dicmAddressData2.setAddressNumber("0");
                        dicmAddressData3.setAddressName("B2");
                        dicmAddressData3.setAddressNumber("0");
                        dicmAddressData4.setAddressName("花溪1");
                        dicmAddressData4.setAddressNumber("0");
                        dicmAddressData5.setAddressName("花溪2");
                        dicmAddressData5.setAddressNumber("0");
                        dicmAddressData6.setAddressName("园区");
                        dicmAddressData6.setAddressNumber("0");
                        dicmAddressData7.setAddressName("仓储");
                        dicmAddressData7.setAddressNumber("0");
                        dicmAddressData8.setAddressName("B1");
                        dicmAddressData8.setAddressNumber("0");
                        dicmAddressDataList.add(dicmAddressData1);
                        dicmAddressDataList.add(dicmAddressData2);
                        dicmAddressDataList.add(dicmAddressData3);
                        dicmAddressDataList.add(dicmAddressData4);
                        dicmAddressDataList.add(dicmAddressData5);
                        dicmAddressDataList.add(dicmAddressData6);
                        dicmAddressDataList.add(dicmAddressData7);
                        dicmAddressDataList.add(dicmAddressData8);
                    }else {
                        String data = JSON.toJSONString(jsonObject.get("data"));
                        Map<String,Object> map = JSONUtil.toBean(data, Map.class);
                        if (CollectionUtil.isNotEmpty(map)){
                            map.forEach((key,value) -> {
                                DicmAddressData addressData = new DicmAddressData();
                                addressData.setAddressName(key);
                                addressData.setAddressNumber(null != value ? value.toString() : "0");
                                addressData.setCreateTime(new Date());
                                dicmAddressDataList.add(addressData);
                            });
                            dicmAddressDataService.saveBatch(dicmAddressDataList);
                        }
                    }
                }else {
                    DicmAddressData dicmAddressData1 = new DicmAddressData();
                    DicmAddressData dicmAddressData2 = new DicmAddressData();
                    DicmAddressData dicmAddressData3 = new DicmAddressData();
                    DicmAddressData dicmAddressData4 = new DicmAddressData();
                    DicmAddressData dicmAddressData5 = new DicmAddressData();
                    DicmAddressData dicmAddressData6 = new DicmAddressData();
                    DicmAddressData dicmAddressData7 = new DicmAddressData();
                    DicmAddressData dicmAddressData8 = new DicmAddressData();
                    dicmAddressData1.setAddressName("A1");
                    dicmAddressData1.setAddressNumber("0");
                    dicmAddressData2.setAddressName("金阳");
                    dicmAddressData2.setAddressNumber("0");
                    dicmAddressData3.setAddressName("B2");
                    dicmAddressData3.setAddressNumber("0");
                    dicmAddressData4.setAddressName("花溪1");
                    dicmAddressData4.setAddressNumber("0");
                    dicmAddressData5.setAddressName("花溪2");
                    dicmAddressData5.setAddressNumber("0");
                    dicmAddressData6.setAddressName("园区");
                    dicmAddressData6.setAddressNumber("0");
                    dicmAddressData7.setAddressName("仓储");
                    dicmAddressData7.setAddressNumber("0");
                    dicmAddressData8.setAddressName("B1");
                    dicmAddressData8.setAddressNumber("0");
                    dicmAddressDataList.add(dicmAddressData1);
                    dicmAddressDataList.add(dicmAddressData2);
                    dicmAddressDataList.add(dicmAddressData3);
                    dicmAddressDataList.add(dicmAddressData4);
                    dicmAddressDataList.add(dicmAddressData5);
                    dicmAddressDataList.add(dicmAddressData6);
                    dicmAddressDataList.add(dicmAddressData7);
                    dicmAddressDataList.add(dicmAddressData8);
                }
            }

            if (CollectionUtil.isNotEmpty(dicmAddressDataList)){
                List<EnergyPueStatisticsVo> finalResulList = resulList;
                dicmAddressDataList.forEach(item -> {
                    EnergyPueStatisticsVo energyPueStatisticsVo = new EnergyPueStatisticsVo();
                    energyPueStatisticsVo.setAddressName(item.getAddressName());
                    energyPueStatisticsVo.setData(item.getAddressNumber().toString());
                    finalResulList.add(energyPueStatisticsVo);
                });
            }
            queryEnergyEfficiencyVo.setPueStatistics(resulList);


//            Calendar calendar = Calendar.getInstance();
//            calendar.setTime(new Date());
//            calendar.add(Calendar.HOUR_OF_DAY,-1);
//            Date time = calendar.getTime();
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
//            String lastDate = sdf.format(time);
////            String nowDate = sdf.format(new Date());
//            String nowDate = sdf.format(new Date());
//            List<QueryLkMqttDataVo> lkMqttDataVos = baseMapper.queryNowMqttDateListByHour(lastDate,addressIdList);
//            if (CollectionUtil.isNotEmpty(lkMqttDataVos)){
////                List<String> siteIdList = lkMqttDataVos.stream().map(QueryLkMqttDataVo::getSiteId).collect(Collectors.toList());
//                Map<String, List<QueryLkMqttDataVo>> map = lkMqttDataVos.stream().collect(Collectors.groupingBy(QueryLkMqttDataVo::getSiteId));
//                List<QueryLkMqttDataVo> lkMqttDataList = baseMapper.queryNowMqttDateListByHour(nowDate,addressIdList);
//                if (CollectionUtil.isNotEmpty(lkMqttDataList)){
//                    Map<String, List<QueryLkMqttDataVo>> mqttDataMap = lkMqttDataList.stream().collect(Collectors.groupingBy(QueryLkMqttDataVo::getSiteId));
//                    resulList = getResulList(addressList,map, mqttDataMap);
//                }
//            }

        }else if (dto.getDataType() == 1) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            Date time = calendar.getTime();
            String lastDate = DateUtil.format(time, DatePattern.NORM_DATE_FORMATTER);
            String nowDate = DateUtil.format(new Date(), DatePattern.NORM_DATE_FORMATTER);
            List<QueryLkMqttDataVo> lkMqttDataVos = baseMapper.queryNowMqttDateList(nowDate,nowDate,addressIdList);
            if (CollectionUtil.isNotEmpty(lkMqttDataVos)){
                List<String> siteIdList = lkMqttDataVos.stream().map(QueryLkMqttDataVo::getSiteId).collect(Collectors.toList());
                Map<String, List<QueryLkMqttDataVo>> map = lkMqttDataVos.stream().collect(Collectors.groupingBy(QueryLkMqttDataVo::getSiteId));
                List<QueryLkMqttDataVo> lkMqttDataList = baseMapper.queryNowMqttDateList(lastDate,lastDate,addressIdList);
                if (CollectionUtil.isNotEmpty(lkMqttDataList)){
                    Map<String, List<QueryLkMqttDataVo>> mqttDataMap = lkMqttDataList.stream().collect(Collectors.groupingBy(QueryLkMqttDataVo::getSiteId));
                    resulList = getResulList(addressList,map, mqttDataMap);
                }
            }

        }else if (dto.getDataType() == 2){
            LocalDate now = LocalDate.now();
            //获取当月时间
            LocalDate nowfirstDay = now.with(TemporalAdjusters.firstDayOfMonth());
            LocalDate nowlastDay = now.with(TemporalAdjusters.lastDayOfMonth());
            Date nowStartTime = Date.from(nowfirstDay.atStartOfDay(ZoneId.systemDefault()).toInstant());
            Date nowEndTime = Date.from(nowlastDay.atStartOfDay(ZoneId.systemDefault()).toInstant());
            String startDate = DateUtil.format(nowStartTime, DatePattern.NORM_DATE_FORMATTER);
            String endDate = DateUtil.format(nowEndTime, DatePattern.NORM_DATE_FORMATTER);
            //获取上月开始时间和结束时间
            now = now.minusMonths(1);
            LocalDate firstDay = now.with(TemporalAdjusters.firstDayOfMonth());
            LocalDate lastDay = now.with(TemporalAdjusters.lastDayOfMonth());
            Date lastStartTime = Date.from(firstDay.atStartOfDay(ZoneId.systemDefault()).toInstant());
            Date lastEndTime = Date.from(lastDay.atStartOfDay(ZoneId.systemDefault()).toInstant());
            String startTime = DateUtil.format(lastStartTime, DatePattern.NORM_DATE_FORMATTER);
            String endTime = DateUtil.format(lastEndTime, DatePattern.NORM_DATE_FORMATTER);
            List<QueryLkMqttDataVo> lkMqttDataVos = baseMapper.queryNowMqttDateList(startDate,endDate,addressIdList);
            if (CollectionUtil.isNotEmpty(lkMqttDataVos)){
                List<String> siteIdList = lkMqttDataVos.stream().map(QueryLkMqttDataVo::getSiteId).collect(Collectors.toList());
                Map<String, List<QueryLkMqttDataVo>> map = lkMqttDataVos.stream().collect(Collectors.groupingBy(QueryLkMqttDataVo::getSiteId));
                List<QueryLkMqttDataVo> lkMqttDataList = baseMapper.queryNowMqttDateList(startTime,endTime,addressIdList);
                if (CollectionUtil.isNotEmpty(lkMqttDataList)){
                    Map<String, List<QueryLkMqttDataVo>> mqttDataMap = lkMqttDataList.stream().collect(Collectors.groupingBy(QueryLkMqttDataVo::getSiteId));
                    resulList = getResulList(addressList,map, mqttDataMap);
                }
            }
        }
//        R<List<Tree<String>>> tree = dicmAddressService.getTree(new DicmAddress());
//        List<Tree<String>> data = tree.getData();
//        Map<String,List<String>> map = new HashMap<>();
//        List<Tree<String>> treeList = (List<Tree<String>>)data.get(0).get("children");
//        if (1 == dto.getType()){
//            for (Tree<String> datum : treeList) {
//                List<String> addressIdList = new ArrayList<>();
//                String addressName = datum.get("label").toString();
//                addressIdList.add(datum.get("id").toString());
////                if (datum.get("name").toString().equals("A1幢机楼")){
////                    addressIdList.add(datum.get("id").toString());
////                }else if ("B1幢机楼".equals(datum.get("name").toString())){
////                    addressIdList.add(datum.get("id").toString());
////                }else if ("B2幢机楼".equals(datum.get("name").toString())){
////                    addressIdList.add(datum.get("id").toString());
////                }else if ("仓储".equals(datum.get("name").toString())){
////                    addressIdList.add(datum.get("id").toString());
////                }else if ("观山湖枢纽楼".equals(datum.get("name").toString())){
////                    addressIdList.add(datum.get("id").toString());
////                }else if ("C2幢机楼".equals(datum.get("name").toString())){
////                    addressIdList.add(datum.get("id").toString());
////                }else if ("花溪枢纽楼".equals(datum.get("name").toString())){
////                    addressIdList.add(datum.get("id").toString());
////                }else if ("花溪枢纽楼B栋".equals(datum.get("name").toString())){
////                    addressIdList.add(datum.get("id").toString());
////                }
//                getAddressIdList((List<Tree<String>>)datum.get("children"),addressIdList);
//                map.put(addressName,addressIdList);
//            }
//        }else if (2 == dto.getType()){
//            for (Tree<String> stringTree : treeList) {
//                if (dto.getAddressId().equals(stringTree.get("id").toString())){
//                    List<Tree<String>> yewuList = (List<Tree<String>>)stringTree.get("children");
//                    if (CollectionUtil.isNotEmpty(yewuList)){
//                        for (Tree<String> stringTree1 : yewuList) {
//                            String addressName = stringTree1.get("label").toString();
//                            if ("业务机房".equals(addressName)){
//                                for (Tree<String> children : (List<Tree<String>>) stringTree1.get("children")) {
//                                    String addressName1 = children.get("label").toString();
//                                    List<String> addressIdList = new ArrayList<>();
//                                    getAddressIdList((List<Tree<String>>)children.get("children"),addressIdList);
//                                    map.put(addressName1,addressIdList);
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//        }
//        List<EnergyPueStatisticsVo> resultList = new ArrayList();
//        List<EnergyPueStatisticsVo> finalResulList = resulList;
//        map.forEach((key, value) -> {
//            EnergyPueStatisticsVo energyPueStatisticsVo = new EnergyPueStatisticsVo();
//            energyPueStatisticsVo.setAddressName(key);
//            BigDecimal energyData = new BigDecimal(0);
//            if (CollectionUtil.isNotEmpty(finalResulList)){
//                for (EnergyPueStatisticsVo pueStatisticsVo : finalResulList) {
//                    if (value.contains(pueStatisticsVo.getAddressId())){
//                        energyData = energyData.add(new BigDecimal(pueStatisticsVo.getData()));
//                    }
//                }
//            }

//            energyPueStatisticsVo.setData(energyData.toString());
//            resultList.add(energyPueStatisticsVo);
//        });
//
//        if (StringUtils.isBlank(queryEnergyEfficiencyVo.getData())){
//            queryEnergyEfficiencyVo.setData("0");
//        }
        queryEnergyEfficiencyVo.setPueStatistics(resulList);
        return R.ok(queryEnergyEfficiencyVo);
    }

    @Override
    public CabinetUsageSituationVo getCabinetTotal(IndexStatisticsDto dto) {
        CabinetUsageSituationVo vo = new CabinetUsageSituationVo();
        R<List<Tree<String>>> tree = dicmAddressService.getTree(new DicmAddress());
        List<Tree<String>> data = tree.getData();
        logger.info("返回资产树结果:{}"+ JSONUtil.parse(data));
        Map<String,List<String>> map = new HashMap<>();
        List<Tree<String>> treeList = (List<Tree<String>>)data.get(0).get("children");
        List<String> addressIdList = new ArrayList<>();
        if (1 == dto.getType()){
            treeList.forEach(item -> {
                getAddressIdList((List<Tree<String>>)item.get("children"),addressIdList);
            });
        }else if (2 == dto.getType()){
            treeList.forEach(item -> {
                if (dto.getAddressId().equals(item.get("id").toString())){
                    List<Tree<String>> treeList1 = (List<Tree<String>>)item.get("children");
                    treeList1.forEach(value -> {
                        getAddressIdList((List<Tree<String>>)value.get("children"),addressIdList);
                    });
                }
            });
        }
        List<DicmCabinet> cabinetList = dicmCabinetService.queryCabinetListById(addressIdList);
        if (CollectionUtil.isNotEmpty(cabinetList)){
            Integer capacity = 0;
            Integer used = 0;
            for (DicmCabinet dicmCabinet : cabinetList) {
                capacity = capacity + Integer.parseInt(dicmCabinet.getUsum());
            }
            vo.setCapacity(capacity);
            List<String> addressNameList = cabinetList.stream().map(DicmCabinet::getAddressId).collect(Collectors.toList());
            List<PostureDevice> deviceList = postureDeviceService.queryDeviceListByCabinet(addressNameList);
            if (CollectionUtil.isNotEmpty(deviceList)){
                Map<String, List<PostureDevice>> map1 = deviceList.stream().collect(Collectors.groupingBy(PostureDevice::getCabinetNum));
                for (String addressName : addressNameList) {
                    if (CollectionUtil.isNotEmpty(map1.get(addressName))){
                        List<PostureDevice> postureDeviceList = map1.get(addressName);
                        for (PostureDevice postureDevice : postureDeviceList) {
                            used = used + postureDevice.getUuse();
                        }
                    }
                }
                vo.setUsed(used);
                vo.setRemaining(capacity - used);
                vo.setCabinetRate(new BigDecimal(used).divide(new BigDecimal(capacity),8, RoundingMode.HALF_UP));
                vo.setCabinetTotal(addressNameList.size());
            }
        }


        return vo;
    }

    @Override
    public List<DicmAddressData> queryEnergyInfo() {
        String date = DateUtil.format(new Date(), "yyyy-MM-dd HH");
        List<DicmAddressData> dicmAddressDataList = dicmAddressDataService.queryEnergyInfoDate(date);
        if (CollectionUtil.isEmpty(dicmAddressDataList)){
            //获取U信息
            com.alibaba.fastjson.JSONObject jsonObject = HttpUtils.sendGetRequest(ApiConstants.IP_ADDRESS
                +ApiConstants.BLADE_ENERGY);
            logger.info("获取能效小时数据返回结果:{}"+JSONUtil.parse(jsonObject));
            if (null != jsonObject){
                if(jsonObject.getInteger("code") == null || jsonObject.getInteger("code").intValue() != 200){
                    DicmAddressData dicmAddressData1 = new DicmAddressData();
                    DicmAddressData dicmAddressData2 = new DicmAddressData();
                    DicmAddressData dicmAddressData3 = new DicmAddressData();
                    DicmAddressData dicmAddressData4 = new DicmAddressData();
                    DicmAddressData dicmAddressData5 = new DicmAddressData();
                    DicmAddressData dicmAddressData6 = new DicmAddressData();
                    DicmAddressData dicmAddressData7 = new DicmAddressData();
                    DicmAddressData dicmAddressData8 = new DicmAddressData();
                    dicmAddressData1.setAddressName("A1");
                    dicmAddressData1.setAddressNumber("0");
                    dicmAddressData2.setAddressName("金阳");
                    dicmAddressData2.setAddressNumber("0");
                    dicmAddressData3.setAddressName("B2");
                    dicmAddressData3.setAddressNumber("0");
                    dicmAddressData4.setAddressName("花溪1");
                    dicmAddressData4.setAddressNumber("0");
                    dicmAddressData5.setAddressName("花溪2");
                    dicmAddressData5.setAddressNumber("0");
                    dicmAddressData6.setAddressName("园区");
                    dicmAddressData6.setAddressNumber("0");
                    dicmAddressData7.setAddressName("仓储");
                    dicmAddressData7.setAddressNumber("0");
                    dicmAddressData8.setAddressName("B1");
                    dicmAddressData8.setAddressNumber("0");
                    dicmAddressDataList.add(dicmAddressData1);
                    dicmAddressDataList.add(dicmAddressData2);
                    dicmAddressDataList.add(dicmAddressData3);
                    dicmAddressDataList.add(dicmAddressData4);
                    dicmAddressDataList.add(dicmAddressData5);
                    dicmAddressDataList.add(dicmAddressData6);
                    dicmAddressDataList.add(dicmAddressData7);
                    dicmAddressDataList.add(dicmAddressData8);
                }else {
                    String data = JSON.toJSONString(jsonObject.get("data"));
                    Map<String,Object> map = JSONUtil.toBean(data, Map.class);
                    if (CollectionUtil.isNotEmpty(map)){
                        map.forEach((key,value) -> {
                            DicmAddressData addressData = new DicmAddressData();
                            addressData.setAddressName(key);
                            addressData.setAddressNumber(null != value ? value.toString() : "0");
                            addressData.setCreateTime(new Date());
                            dicmAddressDataList.add(addressData);
                        });
                    }
                }
            }else {
                DicmAddressData dicmAddressData1 = new DicmAddressData();
                DicmAddressData dicmAddressData2 = new DicmAddressData();
                DicmAddressData dicmAddressData3 = new DicmAddressData();
                DicmAddressData dicmAddressData4 = new DicmAddressData();
                DicmAddressData dicmAddressData5 = new DicmAddressData();
                DicmAddressData dicmAddressData6 = new DicmAddressData();
                DicmAddressData dicmAddressData7 = new DicmAddressData();
                DicmAddressData dicmAddressData8 = new DicmAddressData();
                dicmAddressData1.setAddressName("A1");
                dicmAddressData1.setAddressNumber("0");
                dicmAddressData2.setAddressName("金阳");
                dicmAddressData2.setAddressNumber("0");
                dicmAddressData3.setAddressName("B2");
                dicmAddressData3.setAddressNumber("0");
                dicmAddressData4.setAddressName("花溪1");
                dicmAddressData4.setAddressNumber("0");
                dicmAddressData5.setAddressName("花溪2");
                dicmAddressData5.setAddressNumber("0");
                dicmAddressData6.setAddressName("园区");
                dicmAddressData6.setAddressNumber("0");
                dicmAddressData7.setAddressName("仓储");
                dicmAddressData7.setAddressNumber("0");
                dicmAddressData8.setAddressName("B1");
                dicmAddressData8.setAddressNumber("0");
                dicmAddressDataList.add(dicmAddressData1);
                dicmAddressDataList.add(dicmAddressData2);
                dicmAddressDataList.add(dicmAddressData3);
                dicmAddressDataList.add(dicmAddressData4);
                dicmAddressDataList.add(dicmAddressData5);
                dicmAddressDataList.add(dicmAddressData6);
                dicmAddressDataList.add(dicmAddressData7);
                dicmAddressDataList.add(dicmAddressData8);
            }
        }
        return dicmAddressDataList;
    }

    public void getAddressIdList(List<Tree<String>> data,List<String> addressIdList){
        data.forEach(item -> {
            addressIdList.add(item.get("id").toString());
            List<Tree<String>> treeList = (List<Tree<String>>)item.get("children");
            if (CollectionUtil.isEmpty(treeList)){
                return;
            }
            getAddressIdList(treeList,addressIdList);
        });
    }

    public List<EnergyPueStatisticsVo> getResulList(List<DicmAddress> dicmAddresseList,Map<String, List<QueryLkMqttDataVo>> map,Map<String, List<QueryLkMqttDataVo>> mqttDataMap){
        List<EnergyPueStatisticsVo> resulList = new ArrayList<>();
        dicmAddresseList.forEach(item -> {
            EnergyPueStatisticsVo energyPueStatisticsVo = new EnergyPueStatisticsVo();
            energyPueStatisticsVo.setAddressName(item.getAddressName());
            energyPueStatisticsVo.setAddressId(item.getAddressId());
            if (CollectionUtil.isNotEmpty(map.get(item.getAddressId())) && CollectionUtil.isNotEmpty(mqttDataMap.get(item.getAddressId()))){
                BigDecimal molecule = getMolecule(map.get(item.getAddressId()), mqttDataMap.get(item.getAddressId()));
                BigDecimal denominator = getSubtraction(map.get(item.getAddressId()), mqttDataMap.get(item.getAddressId()));
                String result = computeEnergyPue(map.get(item.getAddressId()).get(0).getExpression(), molecule, denominator);
                energyPueStatisticsVo.setData(result);
            }
            resulList.add(energyPueStatisticsVo);
        });
        return resulList;
    }

    public List<EnergyPueStatisticsVo> getResul(Map<String, List<QueryLkMqttDataVo>> map,Map<String, List<QueryLkMqttDataVo>> mqttDataMap,List<String> siteIdList){
        List<EnergyPueStatisticsVo> resulList = new ArrayList<>();
        siteIdList.forEach(siteId -> {
            EnergyPueStatisticsVo energyPueStatisticsVo = new EnergyPueStatisticsVo();
            energyPueStatisticsVo.setAddressId(map.get(siteId).get(0).getSiteId());
            energyPueStatisticsVo.setAddressName(map.get(siteId).get(0).getSiteName());
            if (CollectionUtil.isNotEmpty(map.get(siteId)) && CollectionUtil.isNotEmpty(mqttDataMap.get(siteId))){
                BigDecimal molecule = getMolecule(map.get(siteId), mqttDataMap.get(siteId));
                BigDecimal denominator = getSubtraction(map.get(siteId), mqttDataMap.get(siteId));
                String result = computeEnergyPue(map.get(siteId).get(0).getExpression(), molecule, denominator);
                energyPueStatisticsVo.setData(result);
            }
            resulList.add(energyPueStatisticsVo);
        });
        return resulList;
    }

    public String computeEnergyPue(String expression, BigDecimal molecule, BigDecimal denominator){
        String subStr = "{0}";
        int index = expression.indexOf(subStr);

        List<Integer> indexList = new ArrayList<>();
        // 使用循环找出所有的位置
        while (index >= 0) {
            indexList.add(index);
//            System.out.println("Found at index: " + index);
////            String message = expression.charAt(index+1)+"";
//            StringBuilder sb = new StringBuilder(expression);
//            sb.replace(index, index + 4, molecule.toString());
//            String message = sb.toString();
//            System.out.println(message);
            // 更新index，继续在剩余的字符串中查找
            index = expression.indexOf(subStr, index + subStr.length());
        }
        if (CollectionUtil.isNotEmpty(indexList)){
            for (int i = 0; i < indexList.size(); i++) {
                if (i == 0){
                    StringBuilder sb = new StringBuilder(expression);
                    sb.replace(indexList.get(i), indexList.get(i) + 3, molecule.toString());
                    expression = sb.toString();
                }else if (i == 1){
                    expression = expression.replace("{0}",denominator.toString());

//                    StringBuilder sb = new StringBuilder(expression);
//                    sb.replace(indexList.get(i)-2, indexList.get(i) + 2, denominator.toString());
//                    expression = sb.toString();
                }
            }
        }
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        BigDecimal bigDecimal = null;
        try {
            String value = engine.eval(expression) + "";
            if (StringUtils.isNotBlank(value) && !value.equals("NaN")){
                BigDecimal bigDecimal1 = new BigDecimal(value);
                bigDecimal = bigDecimal1.setScale(2, RoundingMode.HALF_UP);
            }else {
                bigDecimal = new BigDecimal(0);
            }
        } catch (ScriptException e) {
            throw new RuntimeException(e);
        }
        return bigDecimal.toString();
    }

    public BigDecimal getMolecule(List<QueryLkMqttDataVo> minuendList,List<QueryLkMqttDataVo> subtractionList) {
//        Pattern pattern = Pattern.compile("\\d+\\.\\d+");
        BigDecimal minuend = new BigDecimal(0);
        for (QueryLkMqttDataVo queryLkMqttDataVo : minuendList) {
//            Matcher matcher = pattern.matcher(queryLkMqttDataVo.getMoleculeValue());
//            String group = matcher.group();
            JSONObject jsonObject = new JSONObject(queryLkMqttDataVo.getMoleculeValue());
            double value = jsonObject.getDouble("0");
            BigDecimal decimal = new BigDecimal(value);
            minuend = minuend.add(decimal);
        }
        BigDecimal subtraction = new BigDecimal(0);
        for (QueryLkMqttDataVo queryLkMqttDataVo : subtractionList) {
//            Matcher matcher1= pattern.matcher(queryLkMqttDataVo.getMoleculeValue());
            JSONObject jsonObject = new JSONObject(queryLkMqttDataVo.getMoleculeValue());
            subtraction = subtraction.add(new BigDecimal(jsonObject.getDouble("0")));
        }
        BigDecimal subtract = minuend.subtract(subtraction);
        return subtract;
    }

    public BigDecimal getSubtraction(List<QueryLkMqttDataVo> minuendList,List<QueryLkMqttDataVo> subtractionList) {
//        Pattern pattern = Pattern.compile("\\d+\\.\\d+");
        BigDecimal minuend = new BigDecimal(0);
        for (QueryLkMqttDataVo queryLkMqttDataVo : minuendList) {
//            Matcher matcher = pattern.matcher(queryLkMqttDataVo.getDenominatorValue());
            JSONObject jsonObject = new JSONObject(queryLkMqttDataVo.getMoleculeValue());
            double value = jsonObject.getDouble("0");
            BigDecimal decimal = new BigDecimal(value);
            minuend = minuend.add(decimal);
        }
        BigDecimal subtraction = new BigDecimal(0);
        for (QueryLkMqttDataVo queryLkMqttDataVo : subtractionList) {
//            Matcher matcher1= pattern.matcher(queryLkMqttDataVo.getDenominatorValue());
            JSONObject jsonObject = new JSONObject(queryLkMqttDataVo.getMoleculeValue());
            subtraction = subtraction.add(new BigDecimal(jsonObject.getDouble("0")));
        }
        BigDecimal subtract = minuend.subtract(subtraction);
        return subtract;
    }
}
